Define functions using equation solutions

An easy fallacy

The following does not work as using SetDelayed, variable replacement for ‘x’ happens before the variable ‘sol’ is evaluated to an expression explicitly containing ‘x’.

Clear[sol,x,y,f]

sol=Solve[x+y==3,y]

f[x_]:=y/.sol[[1]]

f[5]
f[6]

DownValues[f]

FullForm[%]

Attributes[SetDelayed]

Attributes[ReplaceAll]

TracePrint[f[5]]

Method 2

Clear[x,y,f,sol];

sol=Solve[x+y==3,y]

sol1=sol[[1]]

f[x_]=y/.sol1

f[5]
f[6]

DownValues[f]

FullForm[%]

TracePrint[f[5]]

Method 3

Clear[x,y,f,sol]

f[x_]:=y/.Solve[x+y==3,y][[1]]

DownValues[f]

TracePrint[f[5]]